<template>
  <el-drawer
    :model-value="isShowAdd"
    size="30%"
    @close="close"
    :close-on-click-modal="false"
  >
    <template #header="{}">
      <div class="flex items-center justify-start">
        <div class="flex items-center justify-center flex-1">
          <p>{{ drawerTitle }}</p>
        </div>
      </div>
    </template>
    <el-form
      v-if="changeShow"
      ref="ruleFormRef"
      :model="addForm"
      :rules="rules"
      label-width="auto"
      label-position="top"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item :label="$t('换汇卖出')" prop="sell_amount">
        <template #label>
          <div class="flex items-center justify-between flex-1">
            <span>{{ $t("换汇卖出") }}</span>
            <span
              >{{ $t("余额") }}：{{
                getBalanceTotal(addForm.sell_currency)?.balance
              }}
              {{ addForm.sell_currency }}</span
            >
          </div>
        </template>
        <el-input
          v-model="addForm.sell_amount"
          type="number"
          placeholder="请输入金额"
          :min="1"
          :step="1"
          @input="handleInput"
          @blur="handleBlur"
        >
          <template #append>
            <el-select
              v-model="addForm.sell_currency"
              placeholder="币种"
              style="width: 100px"
              :popper-class="'userSelect'"
              @change="change_sellCurrency"
              placement="bottom-end"
            >
              <el-option
                v-for="(item, index) in currencyList"
                :key="index"
                :label="item.name"
                :value="item.symbol"
                class="mb-3"
              >
                <div class="flex flex-col justify-start">
                  <p class="h-[26px]">{{ item.name }}</p>
                  <p class="text-[#8f8d8d]">
                    {{ $t("余额") }}: {{ item.balance }}
                  </p>
                </div>
              </el-option>
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="flex items-center justify-center flex-1">
          <div class="flex items-center justify-center exchange-icon">
            <el-icon
              style="font-size: 24px; cursor: pointer"
              @click="handleSort"
              ><Sort
            /></el-icon>
          </div>
          <p
            class="flex flex-col w-[50%] ml-4"
            v-if="addForm.buy_currency && addForm.sell_currency"
          >
            <span>{{ $t("参考汇率") }}</span>
            <span>
              1
              <el-text class="bg-gray-100">{{ addForm.sell_currency }}</el-text>
              =
              {{ exchangePrice }}
              <el-text class="bg-gray-100">{{ addForm.buy_currency }}</el-text>
            </span>
            <span>
              1
              <el-text class="bg-gray-100">{{ addForm.buy_currency }}</el-text>
              =
              {{ exchangePrice1 }}
              <el-text class="bg-gray-100">{{ addForm.sell_currency }}</el-text>
            </span>
          </p>
        </div>
      </el-form-item>
      <el-form-item :label="$t('换汇买入')" prop="buy_amount">
        <template #label>
          <div class="flex items-center justify-between flex-1">
            <span>{{ $t("换汇买入") }}</span>
            <span
              >{{ $t("余额") }}：
              {{ getBalanceTotal(addForm.buy_currency)?.balance }}
              {{ addForm.buy_currency }}</span
            >
          </div>
        </template>
        <el-input
          v-model="addForm.buy_amount"
          type="number"
          placeholder="请输入金额"
          :min="1"
          :step="1"
          @input="handleInput1"
          @blur="handleBlur1"
        >
          <template #append>
            <el-select
              v-model="addForm.buy_currency"
              placeholder="币种"
              popper-class="userSelect"
              @change="change_buyCurrency"
              style="width: 100px"
              placement="bottom-end"
            >
              <el-option
                v-for="(item, index) in currencyList"
                :key="index"
                :label="item.name"
                :value="item.symbol"
                class="mb-3"
              >
                <div class="custom-option">
                  <p class="h-[26px]">{{ item.name }}</p>
                  <p class="text-[#8f8d8d]">
                    {{ $t("余额") }}: {{ item.balance }}
                  </p>
                </div>
              </el-option>
            </el-select>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('换汇时间')" prop="exchange_time">
        <el-date-picker
          v-model="addForm.exchange_time"
          type="datetime"
          :placeholder="$t('请选择换汇时间')"
          style="width: 100%"
        />
      </el-form-item>
      <div class="flex items-center justify-center mt-20">
        <el-button
          type="danger"
          class="w-40 custom-button"
          @click="next(ruleFormRef)"
          >{{ $t("下一步") }}</el-button
        >
      </div>
    </el-form>
    <div v-else>
      <el-card>
        <p>{{ $t("换汇卖出金额") }}</p>
        <p class="mt-2 text-xl">
          {{ addForm.sell_amount }}
          <span class="ml-2">{{ addForm.sell_currency }}</span>
        </p>
        <p class="text-[#8f8d8d]">
          {{ $t("余额") }}：{{
            getBalanceTotal(addForm.sell_currency)?.balance
          }}
          {{ addForm.sell_currency }}
        </p>
      </el-card>
      <div class="flex items-center justify-center flex-1">
        <div class="flex items-center justify-center exchange-icon">
          <el-icon style="font-size: 24px"><Sort /></el-icon>
        </div>
        <p
          class="flex flex-col mt-6 mb-6 w-[50%] ml-4"
          v-if="addForm.buy_currency && addForm.sell_currency"
        >
          <span>{{ $t("参考汇率") }}</span>
          <span>
            1
            <el-text class="bg-gray-100">{{ addForm.sell_currency }}</el-text>
            =
            {{ exchangePrice }}
            <el-text class="bg-gray-100">{{ addForm.buy_currency }}</el-text>
          </span>
          <span>
            1
            <el-text class="bg-gray-100">{{ addForm.buy_currency }}</el-text>
            =
            {{ exchangePrice1 }}
            <el-text class="bg-gray-100">{{ addForm.sell_currency }}</el-text>
          </span>
        </p>
      </div>
      <el-card class="mb-4">
        <p>{{ $t("换汇买入金额") }}</p>
        <p class="mt-2 text-xl">
          {{ addForm.buy_amount }}
          <span class="ml-2">{{ addForm.buy_currency }}</span>
        </p>
        <p class="text-[#8f8d8d]">
          {{ $t("余额") }}：{{ getBalanceTotal(addForm.buy_currency)?.balance }}
          {{ addForm.buy_currency }}
        </p>
      </el-card>
      <el-card class="mb-4">
        <p>{{ $t("换汇时间") }}</p>
        <p class="mt-2 text-xl">
          {{ formatDates(timestamp(addForm.exchange_time.valueOf())) }}
        </p>
      </el-card>
      <div
        class="p-2 flex justify-start mt-4 items-center bg-[#f0f9ff] h-[40px] rounded-lg"
      >
        <div class="flex items-center justify-center">
          <el-icon class="iconInfo"><InfoFilled /></el-icon>
        </div>
        <p class="ml-2 info">
          {{ $t("一经确认，换汇操作无法被取消") }}
        </p>
      </div>
      <div
        v-if="isDangerShow"
        class="p-2 flex justify-start mt-4 items-center bg-[#f0f9ff] h-[60px] rounded-lg"
      >
        <div class="flex items-center justify-center">
          <el-icon class="iconDanger"><WarnTriangleFilled /></el-icon>
        </div>
        <p class="ml-2 info">
          {{
            $t(
              "抱歉，由于您的账户余额不足，我们无法继续您的请求。请充值足够金额至您的钱包之后重试"
            )
          }}
        </p>
      </div>
      <div class="flex items-center justify-center mt-12">
        <el-button type="danger" class="w-40 custom-button" @click="submit">{{
          $t("提交")
        }}</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, watch } from "vue";
import {
  exchangePriceNewApi,
  exchangeStartNewApi,
  getCurrencyNewApi,
} from "@/api/exchange/index";
import { Sort, WarnTriangleFilled, InfoFilled } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
import { timestamp, formatDates } from "@/utils/utils";
const props = defineProps({
  isShowAdd: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["closeAddExchange", "refreshList"]);
const close = () => {
  addForm.sell_amount = "";
  addForm.buy_amount = "";
  addForm.exchange_time = "";
  ruleFormRef.value?.resetFields();
  emits("closeAddExchange");
};

const drawerTitle = ref(t("新增换汇"));

const addForm = reactive({
  sell_amount: "",
  buy_amount: "",
  exchange_time: "",
});
const ruleFormRef = ref();
const currencyList = ref([]); // 币种
const exchangePrice = ref(0);
const exchangePrice1 = ref(0);
const changeShow = ref(true);

watch(
  () => props.isShowAdd,
  (val) => {
    if (val) {
      getCurrencyData();
    }
  }
);

// 获取币种
const getCurrencyData = async () => {
  const res = await getCurrencyNewApi();
  currencyList.value = res.currency;
};

// 监听 buy_currency 和 sell_currency 的变化
watch(
  [() => addForm.buy_currency, () => addForm.sell_currency],
  async ([buyCurrency, sellCurrency]) => {
    if (buyCurrency && sellCurrency) {
      // 在这里进行 exchangePriceNewApi 请求并将结果赋值给 addForm.price
      try {
        const response = await exchangePriceNewApi({
          buy_currency: buyCurrency,
          sell_currency: sellCurrency,
        });
        exchangePrice.value = response.price;
        exchangePrice1.value = response.price1;
      } catch (error) {
        // 处理请求错误
        console.error("Error fetching exchange price: ", error);
        exchangePrice.value = 0;
        exchangePrice1.value = 0;
      }
    } else {
      exchangePrice.value = 0;
      exchangePrice1.value = 0;
    }
  }
);

watch(
  () => exchangePrice.value,
  (exchangePrice) => {
    if (addForm.sell_amount) {
      addForm.buy_amount = (
        Number(addForm.sell_amount) * exchangePrice
      ).toFixed(2);
    }
  }
);

watch(
  () => props.isShowAdd,
  (val) => {
    if (val) {
      changeShow.value = true;
    }
  }
);

watch(
  () => changeShow.value,
  (val) => {
    if (val) {
      drawerTitle.value = t("新增换汇");
    } else {
      drawerTitle.value = t("确认换汇");
    }
  }
);

watch(
  () => addForm.sell_currency,
  (val) => {
    sessionStorage.setItem("selectedSellOption", addForm.sell_currency);
  }
);

watch(
  () => addForm.buy_currency,
  (val) => {
    sessionStorage.setItem("selectedBuyOption", addForm.buy_currency);
  }
);

watch(
  () => currencyList.value,
  (val) => {
    currencyList.value = val;
    addForm.sell_currency = val[0].symbol || "";
    addForm.buy_currency = val[1].symbol || "";
    sessionStorage.setItem("selectedSellOption", addForm.sell_currency);
    sessionStorage.setItem("selectedBuyOption", addForm.buy_currency);
  },
  { deep: true }
);

const change_sellCurrency = (newValue) => {
  let str = sessionStorage.getItem("selectedSellOption") || "";
  if (str !== newValue && addForm.buy_currency !== newValue) {
    sessionStorage.setItem("selectedSellOption", newValue);
  }
  if (addForm.buy_currency === newValue) {
    const temp = addForm.buy_currency;
    addForm.buy_currency = sessionStorage.getItem("selectedSellOption");
    addForm.sell_currency = temp;
    sessionStorage.setItem("selectedBuyOption", addForm.buy_currency);
    sessionStorage.setItem("selectedSellOption", addForm.sell_currency);
  }
  addForm.buy_amount = (
    Number(addForm.sell_amount) * exchangePrice.value
  ).toFixed(2);
};

const change_buyCurrency = (newValue) => {
  let str = sessionStorage.getItem("selectedBuyOption") || "";
  if (str !== newValue && addForm.sell_currency !== newValue) {
    sessionStorage.setItem("selectedBuyOption", newValue);
  }
  if (addForm.sell_currency === newValue) {
    const temp = addForm.sell_currency;
    addForm.sell_currency = sessionStorage.getItem("selectedBuyOption");
    addForm.buy_currency = temp;
  }
  addForm.buy_amount = (
    Number(addForm.sell_amount) * exchangePrice.value
  ).toFixed(2);
};

// 转换
const handleSort = () => {
  const str = addForm.sell_currency;
  addForm.sell_amount = addForm.buy_amount;
  addForm.sell_currency = addForm.buy_currency;
  addForm.buy_currency = str;
};

const getBalanceTotal = (val) => {
  return currencyList.value.find((item) => {
    return item.symbol === val;
  });
};

const handleInput = (value) => {
  // 移除非数字和负号字符
  const sanitizedValue = value.replace(/[^\d\.]/g, "");
  addForm.sell_amount = sanitizedValue;
  addForm.buy_amount = (
    Number(addForm.sell_amount) * exchangePrice.value
  ).toFixed(2);
};
const handleBlur = () => {
  // 确保输入值不为空并且大于等于1
  if (parseFloat(addForm.sell_amount, 10) < 0) {
    addForm.sell_amount = 1; // 默认值为1
  }
};

const handleInput1 = (value) => {
  // 移除非数字和负号字符
  const sanitizedValue = value.replace(/[^\d\.]/g, "");
  addForm.buy_amount = sanitizedValue;
  addForm.sell_amount = (
    Number(addForm.buy_amount) * exchangePrice1.value
  ).toFixed(2);
};
const handleBlur1 = () => {
  // 确保输入值不为空并且大于等于1
  if (parseFloat(addForm.buy_amount, 10) < 1) {
    addForm.buy_amount = 1; // 默认值为1
  }
};

const next = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      changeShow.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

const submit = async () => {
  if (
    Number(addForm.sell_amount) >
    Number(getBalanceTotal(addForm.sell_currency).balance)
  ) {
    isDangerShow.value = true;
  } else {
    isDangerShow.value = false;
    let query = {
      ...addForm,
    };
    query.exchange_time = timestamp(query.exchange_time.valueOf());
    try {
      // 提交数据
      const res = await exchangeStartNewApi(query);
      if (res) {
        ElMessage({
          showClose: true,
          message: t("换汇成功"),
          type: "success",
        });
        emits("refreshList");
      }
    } catch (error) {}
  }
};

const isDangerShow = ref(false);

const rules = reactive({
  sell_amount: [
    { required: true, message: t("请输入卖出金额"), trigger: "blur" },
  ],
  buy_amount: [
    { required: true, message: t("请输入买入金额"), trigger: "blur" },
  ],
  exchange_time: [
    { required: true, message: t("请选择换汇时间"), trigger: "change" },
  ],
});
</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}
.exchange-icon {
  border-radius: 50%;
  background-color: #e54c60;
  color: #fff;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  margin-right: 10px;
  .text {
    display: inline-block;
    line-height: 14px;
  }
}
.userSelect .el-select-dropdown__item {
  min-width: 100px !important;
  height: 45px !important;
  //   padding: 0 5px 0 5px !important;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.userSelect .custom-option {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 3px; /* 这里使用 margin 替代类名 mb-3 */
}

.custom-button {
  background-color: #e54c60 !important;
  border-color: #e54c60 !important;
  color: #fff !important;
}
.custom-button:hover,
.custom-button:focus,
.custom-button:active {
  background-color: #e54c60 !important; /* 点击时的背景色，!important 是为了确保覆盖 Element UI 默认样式 */
  border-color: #e54c60 !important; /* 点击时的边框颜色 */
  color: #fff !important; /* 点击时的文字颜色 */
}
.alertInfo {
  background: #f0f9ff;
  color: #333;
  margin-bottom: 15px;
}
.iconDanger {
  color: #fe5042;
  font-size: 20px;
}
.iconInfo {
  color: #18a6e9;
  font-size: 20px;
}
.info {
  color: #333;
  font-size: 14px;
}
</style>
